// waybillInfoList:[{
//   id:null, 运单id
//   weight:'', 重量
//   volume:'', 体积
//   remark:'', 操作备注
//   picUrl:'' 签收场景-签收图片地址
// }]
// scan_start_next.json
// actionCode 操作编码 EXPRESS_SEND发件, EXPRESS_DELIVERY派件, EXPRESS_SIGN签收, EXPRESS_CANCEL拦截, EXPRESS_MEASURE称重量方, EXPRESS_PACKAGE装箱打包

// scan_end_before.json
// actionCode    操作编码 EXPRESS_RECEIVE收件, EXPRESS_ARRIVE到件
import emitOnFunction from '@/mixin/emit-on-function';
import ExcelJS from '@/asset/exceljs.bare.min.js'
let emitKey = 'tms>>autoFocus'
export default {
  mixins: [emitOnFunction(emitKey)],
  data() {
    return {
      selection: [],
      autoFocus: true,
      autoFocusSet: false,
      autoPrint: false,
      formData: {
        autoWeight:'',
        trackNumber: '',
        placeId: '',
        // 物流方式
        transportType: '',
        // 运费
        expressFee: '',
        // 取件员
        pickUpUsername: '',
        // 支付方式
        payType: '',
        // 目的地
        endAddress: '',
        // 重量
        totalWeight: '',
        // 网点名称
        placeName: '',
        // 客户名称
        customerName: '',
        // 箱号
        packageNo: '',
        // 备注
        remark: '',
        // 派件人
        deliveryUserName:'',
        deliveryUserId:'',
      },
      rules: {
        placeId: {
          required: true, trigger: ['blur', 'change'], message: this.$tt('tip_can_no_empty'),
        },
        trackNumber: {
          required: true, trigger: 'blur', message: this.$tt('tip_can_no_empty'),
        },
        packageNo: [{ required: true, message: this.$t('tip_can_no_empty'), trigger: 'blur' },],
        code: [{ required: true, message: this.$t('tip_can_no_empty'), trigger: 'blur' },],
        deliveryUserId: [{ required: true, message: this.$t('tip_can_no_empty'), trigger: 'blur' },],
      },
      formTable: {
        tableData: []
      },
      formTableRules: {
        trackNumber: [{ required: true, message: this.$t('tip_can_no_empty'), trigger: 'blur' },],
        placeId: [{ required: true, message: this.$t('tip_can_no_empty'), trigger: 'blur' },],
        totalWeight: [{ required: true, message: this.$t('tip_can_no_empty'), trigger: 'blur' },],
        totalVolume: [{ required: true, message: this.$t('tip_can_no_empty'), trigger: 'blur' },],
        packageNo: [{ required: true, message: this.$t('tip_can_no_empty'), trigger: 'blur' },],
      },
    }
  },
  mounted() {
    if (this.$refs.codeInput) {
      this.$refs.codeInput.focus()
    }
  },
  methods: {
    autoFocusSetChange() {
      console.log(this.$refs.codeInput)
      if (this.autoFocusSet) {
        this.$refs.codeInput.focus()
      }
    },
    blurCodeInput(e) {
      if (this.autoFocusSet) {
        if (this.autoFocus) {
          this.$refs.codeInput.select(this.formData.code)
          this.$refs.codeInput.focus()
        }
      }

    },
    scanCodeKeyInput(e) {
      if (e.code == "Enter" || e.key == "Enter") {
        if (this.autoFocusSet) {
          this.$refs.codeInput.select(this.formData.code)
        }
        this.validtrackNumber()
      }
    },
    validtrackNumber() {
      const every = this.formTable.tableData.every(item => (item.transportNumber + '') !== this.formData.code)

      if (!every) {
        this.$message.error(this.$t('tip_no_repeat'))
      } else {
        this.scanPackageNo()
      }
    },
    networkDefault(data) {
      // if(data.length>0){
      //   this.$set(this.formData,'placeId',data[0].id)
      // }else{
      //   this.$set(this.formData,'placeId',null)
      // }
    },
    // 扫码后查询
    scanPackageNo() {
      this.$refs.formSearch.validate((valid) => {
        if (valid) {
          this.$ajax({
            url: this.scanPackageNoUrl,
            method: 'post',
            type: 'form',
            data: {
              placeId: this.formData.placeId,
              code: this.formData.code||this.formData.trackNumber,
              actionCode: this.formData.actionCode
            },
            success: async (res) => {
              if (res && res.data && res.data.rows.length > 0) {
                const resPromise = res.data.rows.map(async item => {
                  let expressFee = item.expressFee
                  // 收件时 没有快速费 就通过接口查询
                  if (this.formData.actionCode === "EXPRESS_RECEIVE") {
                    try {
                      expressFee = await this.getExpressFee({ ...item, totalWeight: res.data.rows.length > 1 ? item.totalWeight : this.formData.autoWeight || item.totalWeight }) || 0
                    } catch (error) {
                      expressFee = 0
                    }

                  }
                  return {
                    ...item,
                    edit: false,
                    scanTime: new Date().getTime(),
                    placeName: this.formData.placeName,
                    packageNo: this.formData.packageNo,
                    // 返回多个时为打包后的包裹 不采用称重
                    totalWeight: res.data.rows.length > 1 ? item.totalWeight : this.formData.autoWeight || item.totalWeight,
                    expressFee: expressFee,
                    currentUsername:this.$loginUser.userName,
                    deliveryUserName:this.formData.deliveryUserName,
                    deliveryUserId:this.formData.deliveryUserId,
                    placeId:this.formData.placeId
                  }
                })
                const data = await Promise.all(resPromise)

                Object.assign(this.formData, data[0])
                this.formTable.tableData.push(...data)

                // 去重
                const map = new Map();
                this.formTable.tableData = this.formTable.tableData.filter(v => !map.has(v.id) && map.set(v.id, v));

                // 自动打印
                if (this.autoPrint) {
                  this.autoPrintFn()
                }

              } else {
                this.$message.error(this.$t('tip_not_found_data'))
              }
            }
          })
        } else {
          return false;
        }
      });
    },
    //获取快递费
    async getExpressFee(orderBoxes) {
      return new Promise((resolve, reject) => {
        this.$ajax({
          url: '/tms-api/waybill/TmsExpressQueryRpc/check_fee.json',
          method: 'post',
          type: "form",
          data: {
            trackId: orderBoxes.trackId,
            volume: orderBoxes.totalVolume,
            weight: orderBoxes.totalWeight
          },
          success: (res) => {
            resolve(res.data.amount + res.data.currencyCode)
          },
          failure: () => {
            reject('错误')
          },
        })
      })
    },
    // 表格编辑
    clickEdit(row) {
      this.$set(row, 'edit', true)
    },
    // 表格保存
    clickEditSave(row) {
      this.$refs['formTableRef'].validate(async (valid, obj) => {
        if (valid) {
          // 编辑时 重新获取快递费
          if (this.formData.actionCode === "EXPRESS_RECEIVE") {
            this.$set(row, 'expressFee', await this.getExpressFee(row))
          }

          this.$set(row, 'edit', false)
        }
      })
    },
    // 表格内删除
    removeBox(index) {
      this.formTable.tableData.splice(index, 1)
    },
    // 批量删除
    deleteFn() {
      if (_.isEmpty(this.selection)) {
        return this.$message.error(this.$tt("tip_please_select_order"));
      }
      const ids = this.selection.map(it => it.trackNumber)
      this.formTable.tableData = this.formTable.tableData.filter(item => !ids.includes(item.trackNumber))
    },
    // 最终的提交
    onSubmit(url, callback) {
      const waybillInfoList = this.selection.length > 0 ? this.selection : this.formTable.tableData
      if (waybillInfoList.length === 0) {
        this.$message.error(this.$t('tip_not_setlect_data'))
        return
      }
      const FINISH = waybillInfoList.every(item => item.status !== 'FINISH')
      const every = waybillInfoList.every(item => !item.edit)
      if (!every) {
        this.$message.error(this.$t('label_edit_submit_tip'))
        return
      }

      if (!FINISH) {
        this.$message.error(this.$t('label_finish_submit_tip'))
        return
      }
      this.$ajax({
        url,
        method: 'post',
        type: "json",
        data: {
          placeId: this.formData.placeId,
          clientType: 'pc',
          packageNo: this.formData.packageNo,
          waybillInfoList: waybillInfoList.map(item => {
            return {
              id: item.id,
              weight:['EXPRESS_RECEIVE','EXPRESS_MEASURE'].includes(this.formData.actionCode)?item.totalWeight:null,
              // volume: ['EXPRESS_RECEIVE','EXPRESS_MEASURE'].includes(this.formData.actionCode)?item.totalVolume:null,
              volume:null,
              remark: item.remark,
              picUrl: item.picUrl,
              deliveryUserName:item.deliveryUserName,
              deliveryUserId:item.deliveryUserId
            }
          })
        },
        success: (res) => {
          this.$message.success(this.$t('tip_submit_success'))

          const ids = waybillInfoList.map(item => item.id)
          this.formTable.tableData = this.formTable.tableData.filter(item => !ids.includes(item.id))
          if (callback) (
            callback()
          )
        },
        failure: () => {
        },
        complete: () => {
        }
      })
    },
    // 导入
    importExcel(e) {
      if (!this.formData.placeId) {
        return this.$message.error(this.$t('label_please_select_branch'))
      }
      this.$uploadFile({
        loading: true,
        url: '/tms-api/waybill/TmsExpressQueryRpc/import_excel.json',
        headers: Object.assign({ 'Content-type': 'multipart/form-data' }, { 'x-place-id': this.formData.placeId }, { 'action-code': this.formData.actionCode }),
        file: e[0],
        success: ({ data }) => {
          if (data.rows) {
            const trackNumbers = data.rows.map(item => item.trackNumber + '')
            const every = this.formTable.tableData.every(item => !trackNumbers.includes(item.trackNumber + ''))

            if (!every) {
              this.$message.error(this.$t('tip_no_repeat'))
              return
            }
            this.formTable.tableData.push(...data.rows)
          }
        }
      })
    },
    // 下载模版
    downloadImportTemp() {
      const model = [
        { key: 'trackNumber', label: 'label_waybill_code', width: 20 },
        { key: 'weight', label: 'label_weight', width: 20 },
        { key: 'volume', label: 'label_volume', width: 20 },
      ]
      const wb = new ExcelJS.Workbook()
      const worksheet = wb.addWorksheet(this.$tt('label_packet_import_temp'))
      worksheet.columns = model.filter(item => item.key).map(it => {
        return { header: this.$tt(it.label), key: it.key, width: it.width }
      });

      wb.xlsx.writeBuffer().then(buffer => {
        this.$downloadBuffer({
          buffer,
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          filename: `${this.$tt('label_packet_import_temp')}${new Date().getTime()}.xlsx`,
        })
      })
    },

    // 导出
    downloadXlsx(filename) {
      let tableData = this.selection.length > 0 ? this.selection : this.formTable.tableData
      tableData = tableData.map(item => {
        return {
          ...item,
          scanTime: this.$dateFormat(item.scanTime),
          transportType: item.transportType ? this.$enumShow(item.transportType, "LogisticsProductsTypeEnum") : '',
          payType: item.payType ? this.$enumShow(item.payType, "TmsOrderPayTypeEnum") : '',
          paymentRequired: item.paymentRequired ? this.$enumShow(item.paymentRequired, "YesOrNoEnum") : '',
          status: item.status ? this.$enumShow(item.status, "TmsWaybillStatusEnum") : '',
        }
      })
      const wb = new ExcelJS.Workbook()
      const worksheet = wb.addWorksheet(this.$tt(filename))
      worksheet.columns = this.tableOption.model.filter(item => item.key).map(it => {
        return { header: this.$tt(it.label), key: it.key, width: it.width }
      });
      worksheet.addRows(tableData);

      wb.xlsx.writeBuffer().then(buffer => {
        this.$downloadBuffer({
          buffer,
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          filename: `${this.$tt(filename)}${new Date().getTime()}.xlsx`,
        })
      })
    }
  }
}
